<template>
  <div class="main-crossSectionalAnalysis">

  </div>
</template>

<script>
import clearWindow from "@/components/js/clearWindow";
import layersMap from "@/components/js/layerMap";
import fetchData from "@/components/js/fetchData";

let line_hdm = null;
let dataset_hdm = []; // 渲染横断面图的数据集
// eslint-disable-next-line no-unused-vars
let layer_hdm = null;
let selectEntity = [];
export default {
  name: "crossSectionalAnalysis",
  components: {},
  data() {
    return {};
  },
  mounted() {
    // 清空面板
    clearWindow();
    this.clearDraw();
    window.viewer.dadi.draw.startDraw({
      "type": "polyline",
      "style": {
        "lineType": "solid",      //线型
        "animationDuration": 1000,      //速度
        "animationImage": "img/textures/lineClr.png",      //图片
        "color": "#3388ff",      //颜色
        "width": 4,      //线宽
        "clampToGround": false,      //是否贴地
        "outline": false,      //是否衬色
        "outlineColor": "#ffffff",      //衬色颜色
        "outlineWidth": 2,      //衬色宽度
        "opacity": 1,      //透明度
        "zIndex": 0,      //层级顺序
      },
      success: (entity) => {
        this.updateSelect_HdmAnalysis(entity);
        this.showLayer_hdm();
      }
    });
  },
  methods: {
    clearDraw() {
      window.viewer.dadi.draw.clearDraw();
      for (var i = 0; i < selectEntity.length; i++) {
        selectEntity[i].billboard.image = 'img/marker/mark3.png';
      }
      selectEntity = [];
      line_hdm = null;
      $('#layerSelect').html('');
    },
    // eslint-disable-next-line no-unused-vars
    updateSelect_HdmAnalysis(drawEntity) {
      // 拿到绘制的geojson
      let drawGeojson = window.viewer.dadi.draw.toGeoJSON()
      line_hdm = turf.feature(drawGeojson.features[0].geometry)
      dataset_hdm = [];
      let count = 0; // 计数器，计算什么时候执行完毕
      layersMap.forEach(async itemObj => {
        let layer = Object.values(window.viewer.dadi.layers).find(l => l.config.id === itemObj.id)
        // console.log(layer)
        if (layer?._visible) {
          const r = await fetchData(itemObj.url)
          // 求交集
          r.features.forEach(fea => {
            let to = turf.feature(fea.geometry)
            let withIntersect = turf.booleanIntersects(to, line_hdm);
            if (withIntersect) {
              const {properties} = fea;
              // 求交点算埋深，水平距离, 垂直距离
              var intersectPoint = turf.lineIntersect(to, line_hdm);
              // console.log(intersectPoint, to);
              let qdms = properties['起点埋深']
              let zdms = properties['终点埋深']
              let qdgc = properties['起点高程']
              let zdgc = properties['终点高程']
              // 算距离和比例
              var fromQd = turf.point(to.geometry.coordinates[0][0].slice(0, -1));
              var fromZd = turf.point(to.geometry.coordinates[0][1].slice(0, -1));
              // var to = turf.point([-75.534, 39.123]);
              var options = {units: 'kilometers'};
              var distance1 = turf.distance(fromQd, (intersectPoint.features)[0], options);
              var distance2 = turf.distance((intersectPoint.features)[0], fromZd, options);
              // console.log(distance1, distance2, distance1 / distance2)

              let currMs = qdms + (zdms - qdms) * (distance1 / distance2) // 相交点埋深
              let currDmgc = qdgc + (zdgc - qdgc) * (distance1 / distance2) // 相交点地面高程
              let currGc = currDmgc - currMs; // 当前管点的高层
              // console.log(qdms, zdms, currMs)
              // 水平间距，垂直间距都是相对第一个的
              let chuizhijianju = 0, shuipingjuli = 0;
              if (dataset_hdm.length > 0) {
                let number1 = dataset_hdm[0];
                chuizhijianju = currGc - number1.guanxiangaocheng;
                shuipingjuli = turf.distance((intersectPoint.features)[0], turf.point(number1.currentCoordianate), options);
              }

              let item = {
                "type": itemObj["type"], // 管线类型
                currentCoordianate: (intersectPoint.features)[0].geometry.coordinates,
                guanxianleixing: properties['材质'],
                bianhao: properties['管线编码'],
                leixing: properties['材质'],
                guanxiangaocheng: currGc.toFixed(4),
                guanxianguige: properties['管径'],
                chuizhijianju: chuizhijianju,
                dimian: currDmgc.toFixed(4),
                guandiangc: currGc.toFixed(4),
                maisheng: currMs.toFixed(4),
                shuipingjuli: shuipingjuli,
                guanjing: properties['管径'],
              }
              dataset_hdm.push(item)
            }
          })
          count++;
        } else {
          count++;
        }
      })

      let timer = setInterval(() => {
        if (count === layersMap.length) {
          window.clearInterval(timer);
          this.rendererHdmChart(dataset_hdm);
        }
      }, 1000)
    },
    rendererHdmChart(dataset) {
      d3.select('#hdm-container svg').remove()

      // 画管线横断面图
      const padding = {
        top: 10,
        left: 50,
        right: 10,
        bottom: 350
      };
      const height = 600;
      const width =document.body.clientWidth - 0;
      const xAxisWidth = width - padding.left - padding.right;
      const yAxisWidth = height - padding.top - padding.bottom;

      const svg = d3.select("#hdm-container")
          .append("svg")
          .attr("width", width)
          .attr("height", height)

      // 先对dataset按水平距离进行排序
      dataset.sort(function (a, b) {
        return a.shuipingjuli - b.shuipingjuli
      });

      var data_dimian = dataset.map(d => d.dimian);
      var data_guandiangc = dataset.map(d => d.guandiangc);
      var data_shuipingjuli = dataset.map(d => d.shuipingjuli);
      var data_guanjing = dataset.map(d => d.guanjing);

      let shuipingGap = d3.max(data_shuipingjuli) - d3.min(data_shuipingjuli)
      const xScale = d3.scaleLinear()

          .domain([d3.min(data_shuipingjuli) - shuipingGap / 3, shuipingGap + shuipingGap / 3])

          .rangeRound([0, xAxisWidth]);

      const yScale = d3.scaleLinear()
          // .domain([0, d3.max(data_dimian) + 10])
          .domain([d3.min(data_guandiangc) - 1, d3.max(data_dimian) + 1])
          .rangeRound([yAxisWidth, 0])
      var rScale = d3.scaleLinear()
          .domain([d3.min(data_guanjing), d3.max(data_guanjing)])
          .range([3, 6]);//将半径映射到2-5,y越大，r越大，但视觉上不合理

      const xAxis = d3.axisBottom(xScale)
          .tickFormat(function (i) {
            return i
          })
      const yAxis = d3.axisLeft(yScale);

      const gx = svg.append("g")
          .attr("transform", `translate(${padding.left}, ${height - padding.bottom})`);
      const gy = svg.append('g')
          .attr("transform", "translate(" + (padding.left) + "," + (padding.top) + ")");

      // 绘制x轴
      gx.call(xAxis)
          .append("text")
          .attr("text-anchor", "start")
          .attr("stroke", "#000000")
          .style("font-size", "17px")
          .style("font-style", "宋体")

      // 绘制y轴
      gy.call(yAxis).append("text")
          .attr("text-anchor", "start")
          .attr("stroke", "#ccc")
          .style("font-size", "14px")
          .style("font-style", "宋体")
          .attr("x", (padding.left - 20))
          .attr("y", 20)
          .text(() => "高程");

      // 可以自动生成颜色
      var color = [];
      for (let i = 0; i < 80; i++) {
        var letters = '0123456789ABCDEF'.split('');
        var rand_color = '#';
        for (var j = 0; j < 6; j++) {
          rand_color += letters[Math.round(Math.random() * 15)];
        }
        color[i] = rand_color;
      }

      // 创建线生成器
      const pathLine = d3.line()
          // .curve(d3.curveBasis) // 如果没有这一行则是折线，有则为曲线
          // .x((d, i) => xScale(i) + padding.left + xScale.bandwidth() / 2)
          .x((d, i) => {
            // console.log(d, xScale(i) , data_shuipingjuli[i] , xScale(data_shuipingjuli[i]))
            return xScale(data_shuipingjuli[i]) - padding.left
            // return xScale(data_shuipingjuli[i])
          })
          // eslint-disable-next-line no-unused-vars
          .y((d, i) => {
            return padding.top + yScale(d)
          });

      var tooltip = d3.select("body")
          .append("div")
          .attr("class", "tooltip")
          .style("background-color", "#d3d3d3")
          .style("border-radius", "3px")
          .style('opacity', 0)
          .style("padding", "5px");

      // 绘制曲线
      svg.append("path")
          .attr("d", pathLine(dataset.map(d => d.dimian)))
          .attr("stroke", '#ccc')
          .attr("stroke-width", "3px")
          .attr("fill", "none")
          .attr("transform", `translate(${(padding.left) * 2},0)`)
          // eslint-disable-next-line no-unused-vars
          .on("mouseover", function (d, i) {
          })
          // eslint-disable-next-line no-unused-vars
          .on("mouseout", function (d, i) {
          });

      // 画散点图
      svg.append("g")   //将所有的circle添加到g元素中，并设置id以后方便引用
          .attr("id", "circles")
          .selectAll("circle")
          .data(data_guandiangc)
          .enter()
          .append("circle")
          .attr("cx", function (d, i) {
            let cx = xScale(data_shuipingjuli[i]);
            let cy = padding.top + yScale(d);
            // 画竖线
            d3.select('#circles').append("path")
                .attr("d", `M${cx},${cy}L${cx},${height}`)
                .attr("stroke", function () {
                  let item = layersMap.find(item => item.type === dataset[i]['type'])
                  return item.color || 'black';
                })
                .attr("stroke-width", "1px")
                .attr("fill", "none")
                .attr("transform", `translate(${(padding.left)},0)`)
            // 写文字
            Object.keys(dataset[i]).forEach(key => {
              let xishu = 0, gap = 40;
              if (key === 'bianhao') {
                xishu = 7
              } else if (key === 'guanxianleixing') {
                xishu = 6
              } else if (key === 'dimian') {
                xishu = 5
              } else if (key === 'guanxiangaocheng') {
                xishu = 4
              } else if (key === 'maisheng') {
                xishu = 3
              } else if (key === 'guanxianguige') {
                xishu = 2
              } else if (key === 'shuipingjuli') {
                xishu = 1
              } else if (key === 'chuizhijianju') {
                xishu = 0
              } else {
                return;
              }
              d3.select('#circles').append("text")
                  // .attr("text-anchor", "start")
                  .attr("fill", "#fff")
                  .style("font-size", "10px")
                  .style("font-style", "宋体")
                  .attr("x", cx)
                  .attr("y", height - xishu * gap - 40)
                  .attr('transform-origin', `${cx} ${height - xishu * gap - 40}`)
                  .attr("transform", `translate(${(padding.left)}, 0) rotate(90)`)
                  // eslint-disable-next-line no-unused-vars
                  .text(d => {
                    let val = dataset[i][key]
                    if (val && Number(val)) {
                      return Number(val).toFixed(2)
                    } else {
                      return val;
                    }
                  });
            })

            return xScale(data_shuipingjuli[i]) + padding.left;
          })
          // eslint-disable-next-line no-unused-vars
          .attr("cy", function (d, i) {
            return padding.top + yScale(d)
          })
          .attr("r", function (d, i) {
            return rScale(data_guanjing[i]);
          })
          .attr("fill",function (d, i) {
            let item = layersMap.find(item => item.type === dataset[i]['type'])
            return item.color || 'black';
          })
          // eslint-disable-next-line no-unused-vars
          .on('click', function (d, i) {

          })
          .on("mouseover", function (d, i) {
            var html = `
            <strong>管线编号: ${dataset[i]['bianhao'] || '-'}</strong><br>
            <strong>管线类型: ${dataset[i]['type'] || '-'}</strong><br>
            <strong>管线材质: ${dataset[i]['leixing'] || '-'}</strong><br>
            <strong>管线高程: ${dataset[i]['guanxiangaocheng'] || '-'}</strong><br>
            <strong>管线埋深: ${dataset[i]['maisheng'] || '-'}</strong><br>
            <strong>管线规格: ${dataset[i]['guanxianguige'] || '-'}</strong><br>
            <strong>水平间距: ${dataset[i]['shuipingjuli'] || '-'}</strong><br>
            <strong>垂直间距: ${dataset[i]['chuizhijianju'] || '-'}</strong><br>
            `;
            // var html = `<strong>编号: ${dataset[i]['bianhao'] || '-'}</strong><br>
            // <strong>管线类型: ${dataset[i]['leixing'] || '-'}</strong><br>
            // <strong>管线高程: ${dataset[i]['guanxiangaocheng'] || '-'}</strong><br>
            // <strong>管线埋深: ${dataset[i]['maisheng'] || '-'}</strong><br>
            // <strong>管线规格: ${dataset[i]['guanxianguige'] || '-'}</strong><br>
            // <strong>水平间距: ${dataset[i]['shuipingjuli'] || '-'}</strong><br>
            // <strong>垂直间距: ${dataset[i]['chuizhijianju'] || '-'}</strong><br>
            // `;
            tooltip.html(html)
                .style("left", (d3.event.pageX + 10) + "px")
                .style("top", (d3.event.pageY + 10) + "px")
                .style("opacity", 1);
          })
          // eslint-disable-next-line no-unused-vars
          .on("mouseout", function (d, i) {
            tooltip.style("opacity", 0);
          });

    },
    showLayer_hdm() {
      if (layer_hdm) return;
      layer_hdm = layui.layer.open({
        type: 1,
        area: [document.body.clientWidth - 0 + 'px', '660px'], // 宽高
        title: "横断面分析", // 不显示标题栏
        offset: ['70px', '0px'],
        closeBtn: 1,
        shade: false,
        shadeClose: false, // 点击遮罩关闭层
        content: `<div id="hdm-container" >
    <div id="hdm" class="mytable">
        <div class="myrow">
            <div>编号</div>
            <div></div>
        </div>
        <div class="myrow">
            <div>管线类型</div>
            <div></div>
        </div>
        <div class="myrow">
            <div>地面高程(m)</div>
            <div></div>
        </div>
        <div class="myrow">
            <div>管线高程(m)</div>
            <div></div>
        </div>
        <div class="myrow">
            <div>管线埋深(m)</div>
            <div></div>
        </div>
        <div class="myrow">
            <div>管线规格(mm)</div>
            <div></div>
        </div>
        <div class="myrow">
            <div>水平间距(m)</div>
            <div></div>
        </div>
        <div class="myrow">
            <div>垂直间距(m)</div>
            <div></div>
        </div>
    </div>
</div>`,
        // eslint-disable-next-line no-unused-vars
        cancel: (index, layero, that) => {
          layer.close(index);
          layer_hdm = null;
          this.$emit('quit')
          return false; // 阻止默认关闭行为
        }
      });
    }
  },
  watch: {},
  computed: {},
  beforeDestroy() {
    this.clearDraw()
    clearWindow()
  },
}
</script>

<style scoped>
.main-crossSectionalAnalysis {
  position: relative;
  height: 100%;
  width: 100%;
}
</style>
